import express from "express";
import { findUserByUsername, updateUser, addUser, findUserById, getUserBookmark, addBookmark, getUserLinks } from "../model/user.js";
import { addBookmarkCnt, getAllTips, delBookmarkCnt } from '../model/links.js'
import multer from "multer";
import fs from 'fs';
const userRouter = express.Router()



//注册
userRouter.post("/register", async (req, res) => {
    const data = req.body;
    console.log(data);
    //如果注册时添加了hobbys
    if (!data.hobbys) {
        data.hobbys = JSON.stringify(data.hobbys);
    }


    const result = await findUserByUsername(data.username)
    if (result) {
        res.send({
            msg: '用户名已注册'
        })
        return;
    }
    else {
        const result = await addUser(data);
        res.send({
            msg: '注册成功',
            user: {
                id: result.id,
                username: result.username
            }

        })
    }
})


//登陆
userRouter.post("/login", async (req, res) => {
    const data = req.body;
    console.log(data);
    const result = await findUserByUsername(data.username)
    if (result === null) {
        res.send({
            status: 'error',
            currentAuthority: 'guest',
            msg: '用户不存在'
        })
        return;
    }
    if (data.password === result.password) {
        //设置cookie
        res.cookie("user", data?.username, { maxAge: 100000 })
        res.cookie("userId", result?.id, { maxAge: 100000 })
        res.send({
            status: 'ok',
            currentAuthority: result.auth === 1 ? "admin" : "user"
        })
        return;
    }
    res.send({
        status: 'error',
        currentAuthority: 'guest',
        msg: '密码错误'
    })
})


//用户个人信息
userRouter.get("/info", async (req, res) => {
    const { userId } = req.cookies;


    const user = await findUserById(Number(userId))

    const allTips = await getAllTips();
    const tipsArr = JSON.parse(user.hobbys)
    const hobbys = tipsArr.map(item => {
        for (let i = 0; i < allTips.length; ++i) {
            if (allTips[i].id == item) return allTips[i];
        }
        return allTips[0]
    })

    res.send({
        msg: "ok",
        data: {
            ...user,
            hobbys,
            bookmark: JSON.parse(user.bookmark)
        }
    })

})

//获取用户收藏
userRouter.get("/getBookmarks", async (req, res) => {
    const { userId } = req.cookies;
    const user = await findUserById(Number(userId));
    const bookmarks = await getUserBookmark(JSON.parse(user.bookmark));

    const allTips = await getAllTips();

    const data = bookmarks.map((item) => {
        const tipsArr = JSON.parse(item.tips)
        const tips = tipsArr.map(item => {
            for (let i = 0; i < allTips.length; ++i) {
                if (allTips[i].id == item) return allTips[i];
            }
        })
        return {
            ...item,
            tips: tips
        }
    })
    res.send({
        msg: 'ok',
        data
    })

})

//获取用户推的链接
userRouter.get("/getMyLinks", async (req, res) => {
    const { userId } = req.cookies;
    const bookmarks = await getUserLinks(Number(userId));

    const allTips = await getAllTips();

    const data = bookmarks.map((item) => {
        const tipsArr = JSON.parse(item.tips)
        const tips = tipsArr.map(item => {
            for (let i = 0; i < allTips.length; ++i) {
                if (allTips[i].id == item) return allTips[i];
            }
        })
        return {
            ...item,
            tips: tips
        }
    })
    res.send({
        msg: 'ok',
        data
    })

})


//获取当前用户
userRouter.get("/current", async (req, res) => {
    console.log(req.cookies);
    const current = req.cookies.userId
    const user = await findUserById(Number(current))
    if (!current) {
        res.status(401).send({
            data: {
                isLogin: false,
            },
            errorCode: '401',
            errorMessage: '请先登录！',
            success: true,
        });
        return
    }
    const hobbys = JSON.parse(user.hobbys)
    const allTips = await getAllTips();
    const tips = hobbys.map(item => {
        for (let i = 0; i < allTips.length; ++i) {
            if (allTips[i].id == item) return allTips[i];
        }
    })


    const bookmark = JSON.parse(user.bookmark)

    res.status(200).send({
        success: true,
        data: {
            ...user,
            hobbys: tips,
            bookmark,
            access: user.auth
        }
    })
})

userRouter.post('/addBookmark', async (req, res) => {
    //获取链接id
    const { id } = req.body;
    const { userId } = req.cookies;
    console.log(userId);

    const user = await findUserById(Number(userId))
    //修改用户bookmark
    const bookmarkArr = JSON.parse(user.bookmark);
    if (bookmarkArr.includes(Number(id))) {
        res.send({
            msg: 'err 用户已经收藏,请勿重复收藏'
        })
        return;
    }
    bookmarkArr.push(Number(id));

    const bookmark = JSON.stringify(bookmarkArr)

    await addBookmark(Number(userId), bookmark)
    await addBookmarkCnt(Number(id))
    //返回成功

    res.send({
        msg: 'ok'
    })
})

userRouter.post('/delBookmark', async (req, res) => {
    //获取链接id
    const { id } = req.body;
    const { userId } = req.cookies;

    const user = await findUserById(Number(userId))

    const bookmarkArr = JSON.parse(user.bookmark);

    if (!bookmarkArr.includes(Number(id))) {
        res.send({
            msg: '用户无收藏'
        })
        return;
    }


    //修改用户bookmark
    const newArr = bookmarkArr.filter(item => {
        if (item === Number(id)) {
            return false;
        }
        return true;
    })

    const bookmark = JSON.stringify(newArr)
    await addBookmark(Number(userId), bookmark)
    await delBookmarkCnt(Number(id))
    //返回成功
    res.send({
        msg: 'ok'
    })
})

userRouter.get("/logout", (req, res) => {
    res.clearCookie('user')
    res.clearCookie('userId')


    res.status(200).send({
        data: {},
        success: true
    })
})
//头像上传

const AvatorStorage = multer.diskStorage({
    //存储路径
    destination: function (req, file, cb) {
        cb(null, '/public/links/icon/');
    },
    //文件名
    filename(req, file, cb) {
        cb(null, file.originalname)
    },
})



const Avatorupload = multer({ AvatorStorage })


userRouter.post('/uploadAvator', Avatorupload.single('file'), (req, res) => {
    //文件会别自动上传到相应目录，并且upload.single('file')会将包含文件信息的对象挂载到req.file上
    const avatorUrl = '/avator/' + req.file.originalname
    fs.writeFileSync(`public/avator/${req.file.originalname}`, req.file.buffer)

    //更新url
    res.send({
        msg: 'ok',
        avatorUrl,
    })

})

//hobbys为标签id数组,标签id切记一点要是number类型
userRouter.post('/updateInfo', async (req, res) => {
    const data = req.body;
    const { userId } = req.cookies
    if (data.hobbys) {
        data.hobbys = JSON.stringify(data.hobbys)
    }
    if (data.auth) {
        delete data.auth
    }
    const result = await updateUser(Number(userId), data)

    res.send({
        msg: 'ok',
        data: result
    })

})


export default userRouter